package com.maweirdos.gulimall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义RabbitMq配置类,将队列、交换机、绑定关系交给Spring容器管理
 * @Author: Maweirdos
 * @Date: 2024/5/20 21:46
 */

@Configuration
public class MyRabbitMqConfig {

    /**
     * 库存服务默认的交换机
     * @return
     */
    @Bean
    public Exchange stockEventExchange(){
        /*
          交换机构造参数String name, boolean durable, boolean autoDelete, Map<String, Object> arguments
         */
        return new TopicExchange("stock-event-exchange", true, false);
    }

    /**
     * 必须首次监听队列，rabbitMQ才会创建队列
     */
    /*@RabbitListener(queues = "stock.release.stock.queue")
    public void handle(Message message) {

    }*/

    /**
     * 普通队列
     * @return
     */
    @Bean
    public Queue stockReleaseStockQueue() {
        //String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
        Queue queue = new Queue("stock.release.stock.queue", true, false, false);
        return queue;
    }

    /**
     * 延迟队列stock.delay.queue
     * @return
     */
    @Bean
    public Queue stockDelay(){
        /*
          队列的全参构造String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
          x-dead-letter-exchange: stock-event-exchange
          x-dead-letter-routing-key: stock.release.stock.queue
          x-message-ttl: 120000
         */
        Map<String,Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange","stock-event-exchange");
        arguments.put("x-dead-letter-routing-key","stock.release");
        arguments.put("x-message-ttl",120000);
        return new Queue("stock.delay.queue", true, false, false,arguments);
    }

    /**
     * 交换机与普通队列绑定
     * @return
     */
    @Bean
    public Binding stockLocked() {
        Binding binding = new Binding("stock.release.stock.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.release.#",
                null);

        return binding;
    }

    /**
     * 交换机与延迟队列绑定
     * @return
     */
    @Bean
    public Binding stockLockedBinding() {
        return new Binding("stock.delay.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.locked",
                null);
    }
}
